#!/usr/bin/env python
#-*- coding:utf-8 -*-

"""
php运行环境
"""

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import os.path

SystemName = 'PHP Server Interface'
SystemVersion = '1.0.0'
SystemUrl = 'http://www.du52.com'
SystemFile = os.path.altsep.join([os.path.abspath(os.path.curdir), 'config.ini'])
SiteHost = '127.0.0.1'
SitePort = 8866
DefaultPort = 8866
SiteRoot = os.path.abspath(os.path.curdir)
PhpRoot = os.path.altsep.join([os.path.abspath(os.path.curdir), 'php', 'php.exe'])

import wx
import resource
import webbrowser
import socket
import subprocess
import ConfigParser

class Service(object):

    def __init__(self):
        self.process = None

    # 检查端口是否可用
    def CheckPort(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(1)
            s.connect((SiteHost,SitePort))
            s.close()
            return False
        except Exception,e:
            return True

    def Start(self, show=True):
        if self.process:
            if show:
                wx.MessageBox('服务已经启动', SystemName)
            return True
        if not self.CheckPort():
            if show:
                wx.MessageBox('端口已被占用,请检查占用端口的程序', SystemName)
            return False

        PhpCommand = '"%s" -S %s:%d -t "%s"'%(PhpRoot, SiteHost, SitePort, SiteRoot)
        try:
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
            startupinfo.wShowWindow = subprocess.SW_HIDE
            self.process = subprocess.Popen(PhpCommand,shell=False,startupinfo=startupinfo,creationflags=subprocess.CREATE_NEW_CONSOLE)
        except Exception,e:
            self.process = None

        if self.process:
            if show:
                wx.MessageBox('服务启动成功', SystemName)
            return True
        if show:
            wx.MessageBox('服务启动失败', SystemName)
            return False

    def Stop(self, show=True):
        if self.process:
            self.process.kill()
            self.process.wait()
            self.process = None
            if show:
                wx.MessageBox('服务已停止', SystemName)
            return True
        else:
            if show:
                wx.MessageBox('服务未启动', SystemName)
            return True

    def Restart(self):
        if self.process:
            self.Stop(False)
        return self.Start()

class TaskBarIcon(wx.TaskBarIcon):

    ID_TITLE = wx.NewId()
    ID_OPEN = wx.NewId()
    ID_START = wx.NewId()
    ID_STOP = wx.NewId()
    ID_RESTART = wx.NewId()
    ID_EXIT = wx.NewId()
    ID_SITE = wx.NewId()

    def __init__(self, frame):
        wx.TaskBarIcon.__init__(self)
        self.frame = frame
        self.service = Service()
        self.SetIcon(resource.icon.getIcon(), SystemName)
        self.Bind(wx.EVT_MENU, self.ExitEvent, id=self.ID_EXIT)
        self.Bind(wx.EVT_MENU, self.SiteEvent, id=self.ID_SITE)
        self.Bind(wx.EVT_MENU, self.RestartEvent, id=self.ID_RESTART)
        self.Bind(wx.EVT_MENU, self.StartEvent, id=self.ID_START)
        self.Bind(wx.EVT_MENU, self.StopEvent, id=self.ID_STOP)
        self.Bind(wx.EVT_MENU, self.OpenEvent, id=self.ID_OPEN)

    def InitEvent(self, event=None):
        if self.service.Start():
            self.OpenEvent()

    def OpenEvent(self, event=None):
        SiteUrl = 'http://%s:%d'%(SiteHost,SitePort)
        webbrowser.open_new(SiteUrl)

    def StopEvent(self, event=None):
        self.service.Stop()

    def StartEvent(self, event=None):
        self.service.Start()

    def RestartEvent(self, event=None):
        self.service.Restart()

    def SiteEvent(self, event=None):
        webbrowser.open_new(SystemUrl)

    def ExitEvent(self, event=None):
        self.service.Stop(False)
        self.frame.Close()

    # override
    def CreatePopupMenu(self):
        menu = wx.Menu()
        menu.Append(self.ID_TITLE, SystemName)
        menu.AppendSeparator();
        menu.Append(self.ID_OPEN, '打开网页')
        menu.Append(self.ID_START, '开启服务')
        menu.Append(self.ID_STOP, '停止服务')
        menu.Append(self.ID_RESTART, '重启服务')
        menu.AppendSeparator()
        menu.Append(self.ID_SITE, '官方网站')
        menu.Append(self.ID_EXIT, '退出程序')
        return menu

class Frame(wx.Frame):

    def __init__(self, parent = None):
        wx.Frame.__init__(self, parent, wx.ID_ANY, SystemName, wx.DefaultPosition, wx.DefaultSize, wx.DEFAULT_FRAME_STYLE)
        self.SetIcon(resource.icon.getIcon())
        self.taskBarIcon = TaskBarIcon(self)
        self.Bind(wx.EVT_CLOSE, self.CloseEvent)
        self.taskBarIcon.InitEvent()

    def CloseEvent(self, event):
        self.taskBarIcon.Destroy()
        self.Destroy()

class App(wx.App):

    def OnInit(self):
        global SitePort
        # 读取配置
        try:
            cp = ConfigParser.ConfigParser()
            cp.read(SystemFile)
            SitePort = int(cp.get('config', 'port'))
        except Exception,e:
            SitePort = DefaultPort
        self.frame = Frame()
        self.frame.Show(False)
        self.SetTopWindow(self.frame)
        return True

if __name__ == '__main__':
    app = App()
    app.MainLoop()

